package com.novunda.platform.common.utils;

import com.novunda.platform.entities.EmailInfo;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

/**
 * 邮件发送工具实现类
 */
public class MailUtil {

    protected final Logger logger = Logger.getLogger(getClass());

    public boolean send(EmailInfo emailInfo, String...receivers) {
        // 发送email  
        HtmlEmail email = new HtmlEmail();
        try {
            // 这里是SMTP发送服务器的名字：163的如下："smtp.163.com"  
            email.setHostName(emailInfo.getServersAddress());
            // 字符编码集的设置
            email.setCharset("UTF-8");
            // 收件人的邮箱  
            email.addTo(receivers);
            //端口
            if (emailInfo.isOpenSSL()){
                email.setSslSmtpPort(emailInfo.getPort() + "");
            }else {
                email.setSmtpPort(emailInfo.getPort());
            }
            email.setSSLOnConnect(emailInfo.isOpenSSL());
            // 发送人的邮箱
            email.setFrom(emailInfo.getEmail());
            // 如果需要认证信息的话，设置认证：用户名-密码。分别为发件人在邮件服务器上的注册名称和密码  
            email.setAuthentication(emailInfo.getEmail(), emailInfo.getEmailPassword());
            // 要发送的邮件主题  
            email.setSubject(emailInfo.getEmailTheme());
            // 要发送的信息，由于使用了HtmlEmail，可以在邮件内容中使用HTML标签  
            email.setMsg("<div>" + emailInfo.getEmailContent() + "</div>" + "<div>" + emailInfo.getEmailRemarks() + "</div>");
            // 发送  
            email.send();
//            if (logger.isDebugEnabled()) {
//                logger.debug(emailInfo.getEmail() + " 发送邮件到 " + receivers.toString());
//            }
            return true;
        } catch (EmailException e) {
//            e.printStackTrace();
            logger.error(e.getMessage(), e);
//            logger.info(emailInfo.getEmail() + " 发送邮件到 " + receivers
//                    + " 失败");
            return false;
        }
    }

}  